import { Login_GetStatus, Login_GetToken } from "./login.js";
import {
    API_GetProjectInfo,
    API_GetProjectList,
    API_GetProjectUrl,
    API_DeleteProject,
    API_SaveXMLFile,
    API_NewProject,
    API_GetFile,
    API_ExportProject,
    API_BaseUrl,
    API_GetProjectFile,
    API_DeleteFile,
    API_CreateView,
} from "./api.js";
import {
    FileMangeUpdate,
    FileMangeGetCurrentFileId,
    FileMangeGetCurrentViewPath,
    FileMangeSetCurrentFileId,
    FileMangeSetCurrentViewPath,
} from "./FileMange.js";
import SlowReminder from "./SlowReminder.js";

var projectInfo = {
    xml_files: [],
    image_files: [],
};

/**
 * 工程状态
 * 0: 当前没有工程
 * 1: 当前有工程
 */
var projectStatus = 0;
var projectElement = null;
var projectIsChange = false;

export function ProjectInit() {
    projectElement = document.getElementById("project");
    projectElement.onclick = () => {
        ProjectCloseBox();
    };
}

/**
 *
 * @returns {boolean} 当前工程是否被修改过
 */
export function ProjectIsChange() {
    return projectIsChange;
}

export function ProjectChange() {
    projectIsChange = true;
    console.log("改变");
}

/**
 * 获取当前工程ID
 * @returns {string} 当前工程ID
 */
export function ProjectGetCurrentId() {
    if (projectStatus == 0) {
        return "";
    }
    if (projectInfo && projectInfo.id) {
        return projectInfo.id;
    }
}

export function ProjectShowBox() {
    console.log("显示工程列表");
    // document.getElementById("project-box").style.display = "flex";
    document.getElementById("app").style.display = "none";
    document.getElementById("project").style.display = "flex";
}

export function ProjectCloseBox() {
    if (Login_GetStatus() == 0) {
        return;
    }
    if (projectStatus == 1) {
        document.getElementById("project").style.display = "none";
        document.getElementById("app").style.display = "flex";
    }
}

export function ProjectCreateView(info) {
    const view = `
                        <div class="project-history-item">
                            <span class="iconfont">&#xe60a;</span>
                            <div class="project-history-item-name">${info.name}</div>
                            <div class="project-history-item-desc">${info.describe}</div>
                            <div class="project-history-item-button" projectId="${info.id}">打开</div>
                            <span class="iconfont project-history-item-del" projectId="${info.id}">&#xe612;</span>
                        </div>
    `;
    return view;
}

export function ProjectCreateXMLView(callback = null) {
    // 输入框
    var name = prompt("请输入视图名称", "");
    if (name == null || name.trim() == "") {
        alert("请输入视图名称");
        return;
    }
    if (isValidString(name) == false) {
        alert("名称不合法");
        return;
    }
    API_CreateView(Login_GetToken(), ProjectGetCurrentId(), name, (res) => {
        if (res.code === 0) {
            console.log("创建视图成功");
            // ProjectUpdateList();
            ProjectUpdateFile(() => {
                FileMangeUpdate();

                // API_GetFile(Login_GetToken(), id, (res) => {
                //     window["layout"].loadXML(res);
                //     document.getElementById("informationBar").innerText = name;
                //     fileMangeCurrentViewPath = path;
                //     fileMangeCurrentFileId = id;
                // });
            });
        } else {
            alert(res.msg);
        }
        if (callback) {
            callback(res);
        }
    });
}

export function ProjectGetInfo(projectId, callback = null) {
    API_GetProjectInfo(Login_GetToken(), projectId, (res) => {
        if (res.code === 0) {
            document.querySelector("#project").style.display = "none";
            document.querySelector("#app").style.display = "flex";
            projectInfo = res.info;
            projectStatus = 1;
            ProjectSeting();
            if (callback) {
                callback(res.info);
            }
        } else {
            alert(res.msg);
        }
    });
}

export function ProjectUpdateFile(callback = null) {
    if (Login_GetStatus() == 0) {
        alert("请先登录");
        return;
    }
    if (projectStatus == 0) {
        alert("当前没有工程");
        return;
    }
    API_GetProjectFile(Login_GetToken(), projectInfo.id, (res) => {
        if (res.code === 0) {
            const files = res.info;
            console.log(files);
            projectInfo.xml_files = files.filter((file) => file.type === "xml");
            projectInfo.image_files = files.filter(
                (file) => file.type === "image"
            );
            // 从新更新属性栏文件选择器
            window.UISetingImageSelector();
            // 加载phaser图片
            // PhaserLoadImageList(ProjectGetImageFiles());
            window["layout"].loadImage(ProjectGetImageFiles());

            if (callback) {
                callback(projectInfo);
            }
        } else {
            alert(res.msg);
        }
    });
}

export function ProjectUpdateList() {
    if (Login_GetStatus() == 0) {
        return;
    }
    API_GetProjectList(Login_GetToken(), (res) => {
        // console.log(res);
        if (res.code == 0) {
            const listDiv = document.getElementById("project-history-content");
            listDiv.innerHTML = "";
            for (let i = 0; i < res.info.length; i++) {
                const info = res.info[i];
                listDiv.innerHTML += ProjectCreateView(info);
            }

            listDiv
                .querySelectorAll(".project-history-item-button")
                .forEach((element) => {
                    element.onclick = (e) => {
                        const projectId =
                            e.currentTarget.getAttribute("projectId");
                        console.log("打开工程", projectId);
                        ProjectGetInfo(projectId);
                    };
                });

            listDiv
                .querySelectorAll(".project-history-item-del")
                .forEach((element) => {
                    element.onclick = (e) => {
                        const projectId =
                            e.currentTarget.getAttribute("projectId");
                        if (confirm("确定删除该工程吗？")) {
                            ProjectDelete(projectId);
                        }
                    };
                });
        }
    });
}

export function ProjectDelete(projectId) {
    if (Login_GetStatus() == 0) {
        alert("请先登录");
        return;
    }
    if (projectStatus == 1 && projectInfo.id == projectId) {
        if (confirm("当前工程正在编辑，是否删除？")) {
            projectInfo = {
                xml_files: [],
                image_files: [],
            };
            projectStatus = 0;
        } else {
            return;
        }
    }
    API_DeleteProject(Login_GetToken(), projectId, (res) => {
        if (res.code === 0) {
            ProjectUpdateList();
        } else {
            alert(res.msg);
        }
    });
}

export function isValidString(str) {
    // const regex = /^[\u4e00-\u9fa5a-zA-Z0-9_]+$/;
    const regex = /^(?![0-9])[\u4e00-\u9fa5a-zA-Z0-9_]+$/;
    return regex.test(str);
}

export function ProjectNew() {
    if (Login_GetStatus() == 0) {
        alert("请先登录");
        return;
    }

    let proname = prompt("请输入工程名称,不建议使用特殊字符命名");
    if (proname == null) {
        return;
    }
    proname = proname.trim();
    if (proname == undefined || proname == "") {
        alert("请输入工程名");
        return;
    }
    if (isValidString(proname) == false) {
        alert("工程名不合法");
        return;
    }

    API_NewProject(Login_GetToken(), proname, "", (res) => {
        if (res.code === 0) {
            document.querySelector("#project").style.display = "none";
            document.querySelector("#app").style.display = "flex";
            projectInfo = res.info;
            console.log("新建工程成功", projectInfo);
            projectStatus = 1;
            ProjectSeting();
        } else {
            alert(res.msg);
        }
    });
}

export function ProjectSave(callback = null) {
    if (projectStatus == 0) {
        console.log("未打开工程");
        return;
    }
    const xmlstr = window["layout"].getXML();
    API_SaveXMLFile(
        Login_GetToken(),
        FileMangeGetCurrentFileId(),
        xmlstr,
        (res) => {
            if (res.code === 0) {
                // alert("保存成功");
                projectIsChange = false;
                if (callback) {
                    callback();
                }
            } else {
                console.log("保存失败", res);
                SlowReminder("保存失败");
            }
        }
    );
}

export function ProjectSeting() {
    console.log(projectInfo);
    window["layout"].setProjectUrl(
        API_GetProjectUrl(Login_GetToken(), ProjectGetCurrentId())
    );
    FileMangeUpdate();

    // 从新设置布局属性栏的图片选择器
    UISetingImageSelector();

    // Phaser加载图片
    window["layout"].loadImage(ProjectGetImageFiles(), () => {
        ProjectOpenDefineView();
    });
    if (projectInfo.image_files.length == 0) {
        ProjectOpenDefineView();
    }
}

/**
 * 打开第一个视图文件
 */
function ProjectOpenDefineView() {
    if (projectInfo.xml_files.length > 0) {
        const firstFile = projectInfo.xml_files[0];
        API_GetFile(localStorage.getItem("token"), firstFile.id, (res) => {
            window["layout"].loadXML(res);
            document.getElementById("informationBar").innerText =
                firstFile.name;
            console.log("打开文件", firstFile);
            FileMangeSetCurrentFileId(firstFile.id);
            FileMangeSetCurrentViewPath(firstFile.path);
        });
    }
}

export function ProjectGetXMLFiles() {
    return projectInfo.xml_files;
}

export function ProjectGetImageFiles() {
    return projectInfo.image_files;
}

export function ProjectRemoveFile(fileId, callback = null) {
    if (Login_GetStatus() == 0) {
        return;
    }
    const token = localStorage.getItem("token");
    API_DeleteFile(token, fileId, (res) => {
        if (res.code === 0) {
            // 从 projectInfo 中删除文件
            const idx = projectInfo.xml_files.findIndex(
                (file) => file.id == fileId
            );
            if (idx !== -1) {
                projectInfo.xml_files.splice(idx, 1);
            }
            const idx2 = projectInfo.image_files.findIndex(
                (file) => file.id == fileId
            );
            if (idx2 !== -1) {
                projectInfo.image_files.splice(idx2, 1);
            }

            if (callback) {
                callback();
            }
        } else {
            alert(res.msg);
        }
    });
}

// 导出数据包
export function ProjectExportPackage() {
    // console.log("导出数据包");

    if (Login_GetStatus() == 0) {
        alert("请先登录");
        return;
    }
    if (projectStatus == 0) {
        alert("当前没有工程");
    }
    if (ProjectIsChange()) {
        if (confirm("当前工程有未保存的修改，是否保存？")) {
            ProjectSave(() => {
                ProjectExportPackage();
            });
        }
        return;
    }

    API_ExportProject(Login_GetToken(), projectInfo.id, (res) => {
        if (res.code === 0) {
            const url = res.info.url;
            console.log(url);
            SlowReminder("导出成功");
            window.open(API_BaseUrl() + "/" + url);
        }
    });
}

export function ProjectImportPackage() {
    console.log("导入数据包");
    alert("暂不支持导入数据");
}

export function ProjectRevoke() {
    console.log("撤销");
}

export function ProjectRedo() {
    console.log("回撤");
}
